import axios from 'axios';

// API基础配置 - 使用绝对路径，通过proxy转发
const API_BASE_URL = '/api';

// 请求缓存，防止重复请求
const requestCache = new Map();

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  },
  withCredentials: true, // 包含cookies，模拟成功的浏览器请求
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    console.error('Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.error('Response Error:', error);
    return Promise.reject(error);
  }
);

// 请求去重辅助函数
const dedupeRequest = async (key, requestFn) => {
  if (requestCache.has(key)) {
    return requestCache.get(key);
  }
  
  const promise = requestFn();
  requestCache.set(key, promise);
  
  try {
    const result = await promise;
    return result;
  } finally {
    // 请求完成后清除缓存，避免内存泄漏
    requestCache.delete(key);
  }
};

// API服务类
export class ApiService {
  // 获取首页轮播图
  static async getTopBannerList() {
    return dedupeRequest('getTopBannerList', async () => {
      try {
        const response = await apiClient.get('/officalsite/getTopBannerList');
        return response;
      } catch (error) {
        console.error('获取轮播图失败:', error);
        throw error;
      }
    });
  }

  // 获取热门产品列表
  static async getHotProductList() {
    return dedupeRequest('getHotProductList', async () => {
      try {
        const response = await apiClient.post('/officalsite/qryHotProductList', {});
        return response;
      } catch (error) {
        console.error('获取热门产品失败:', error);
        throw error;
      }
    });
  }

  // 获取产品大类列表
  static async getMainCategoryList() {
    return dedupeRequest('getMainCategoryList', async () => {
      try {
        const response = await apiClient.post('/officalsite/qryMainCategoryList', {});
        return response;
      } catch (error) {
        console.error('获取产品大类失败:', error);
        throw error;
      }
    });
  }

  // 获取产品大类下的产品列表
  static async getCategoryProductList(categoryId) {
    return dedupeRequest(`getCategoryProductList_${categoryId}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/qryCategoryProductList', {
          categoryId: categoryId
        });
        return response;
      } catch (error) {
        console.error('获取产品大类下产品失败:', error);
        throw error;
      }
    });
  }

  // 获取产品详情
  static async getProductDetail(productId) {
    return dedupeRequest(`getProductDetail_${productId}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/qryProductDetail', {
          productId: productId
        });
        return response;
      } catch (error) {
        console.error('获取产品详情失败:', error);
        throw error;
      }
    });
  }

  // 分页查询产品大类下产品列表
  static async getCategoryProductListPage(categoryId, pageIndex = 1, pageSize = 10) {
    return dedupeRequest(`getCategoryProductListPage_${categoryId}_${pageIndex}_${pageSize}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/qryCategoryProductListPage', {
          pageIndex: pageIndex,
          pageSize: pageSize,
          param: {
            categoryId: categoryId || ''
          }
        });
        return response;
      } catch (error) {
        console.error('获取产品列表失败:', error);
        throw error;
      }
    });
  }

  // 分页查询行业资讯列表
  static async getIndustryNewsListPage(pageIndex = 1, pageSize = 10) {
    return dedupeRequest(`getIndustryNewsListPage_${pageIndex}_${pageSize}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/qryIndustryNewsListPage', {
          pageIndex: pageIndex,
          pageSize: pageSize,
          param: {}
        });
        return response;
      } catch (error) {
        console.error('获取行业资讯列表失败:', error);
        throw error;
      }
    });
  }

  // 查询行业资讯详情
  static async getIndustryNewsDetail(newsId) {
    return dedupeRequest(`getIndustryNewsDetail_${newsId}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/qryIndustryNewsDetail', {
          newsId: newsId
        });
        return response;
      } catch (error) {
        console.error('获取行业资讯详情失败:', error);
        throw error;
      }
    });
  }

  // 分页查询解决方案列表
  static async getSolutionsListPage(pageIndex = 1, pageSize = 10) {
    return dedupeRequest(`getSolutionsListPage_${pageIndex}_${pageSize}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/qryIndustryNewsListPage', {
          pageIndex: pageIndex,
          pageSize: pageSize,
          param: {}
        });
        return response;
      } catch (error) {
        console.error('获取解决方案列表失败:', error);
        throw error;
      }
    });
  }

  // 查询解决方案列表（不分页）
  static async getSolutionsList() {
    return dedupeRequest('getSolutionsList', async () => {
      try {
        const response = await apiClient.post('/officalsite/qryIndustryNewsList', {
          param: {}
        });
        return response;
      } catch (error) {
        console.error('获取解决方案列表失败:', error);
        throw error;
      }
    });
  }

  // 分页查询资料列表
  static async getDocumentListPage(pageIndex = 1, pageSize = 10) {
    return dedupeRequest(`getDocumentListPage_${pageIndex}_${pageSize}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/qryDocumentListPage', {
          pageIndex: pageIndex,
          pageSize: pageSize,
          param: {}
        });
        return response;
      } catch (error) {
        console.error('获取资料列表失败:', error);
        throw error;
      }
    });
  }

  // 获取验证码
  static async getVerificationCode() {
    return dedupeRequest('getVerificationCode', async () => {
      try {
        const response = await apiClient.post('/officalsite/getVerificationCode', {
          param: {}
        });
        return response;
      } catch (error) {
        console.error('获取验证码失败:', error);
        throw error;
      }
    });
  }

  // 提交留言
  static async submitCommentMessage(title, content, email, verificationCode, eventId) {
    return dedupeRequest(`submitCommentMessage_${eventId}`, async () => {
      try {
        const response = await apiClient.post('/officalsite/subCommentMessage', {
          title: title,
          content: content,
          email: email,
          verificationCode: verificationCode,
          eventId: eventId
        });
        return response;
      } catch (error) {
        console.error('提交留言失败:', error);
        throw error;
      }
    });
  }

  // 查询公司详情
  static async getCompanyDetail() {
    return dedupeRequest('getCompanyDetail', async () => {
      try {
        const response = await apiClient.post('/officalsite/qryCompanyDetail', {});
        return response;
      } catch (error) {
        console.error('获取公司详情失败:', error);
        throw error;
      }
    });
  }

  // 查询合作品牌列表
  static async getCooperativeBrandList() {
    return dedupeRequest('getCooperativeBrandList', async () => {
      try {
        const response = await apiClient.post('/officalsite/qryCooperativeBrandList', {});
        return response;
      } catch (error) {
        console.error('获取合作品牌列表失败:', error);
        throw error;
      }
    });
  }

  // 查询行业资讯列表（不分页）
  static async getIndustryNewsList() {
    return dedupeRequest('getIndustryNewsList', async () => {
      try {
        const response = await apiClient.post('/officalsite/qryIndustryNewsList', {});
        return response;
      } catch (error) {
        console.error('获取行业资讯列表失败:', error);
        throw error;
      }
    });
  }

}

export default ApiService;
